from bs4 import BeautifulSoup
html_doc = """
<html><head><title id="one">The Dormouse's story</title></head>
<body>
<p class="story"><!--fssfsffda..sdfafaff--></p>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""
#1.转换类型
soup=BeautifulSoup(html_doc,'lxml')

#2.通用解析方法

#find--反回符合条件的第一个数据(第一个标签)
result=soup.find(name='a')
print(result)#<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
result=soup.find(attrs={"class":"title"})
print(result.text)#<p class="title"><b>The Dormouse's story</b></p>
print('=='*100)
result=soup.find(name='p',attrs={"class":"story"})
print(result)


#findall--返回列表(所有的标签对象)
result=soup.find_all('a')#[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
print(result)

result=soup.find_all('a',limit=1)
print(result)

result=soup.find_all(attrs={"class":"sister"})
print(result)


#select_one  :css选择器
result=soup.select_one('.sister')
print(result)#<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>

#select--返回列表
result=soup.select('.sister')
print(result)

result=soup.select('#one')#id 选择器
print(result)#[<title id="one">The Dormouse's story</title>]

result=soup.select('head title')#后代选择器
print(result)#[<title id="one">The Dormouse's story</title>]

result=soup.select('title,.title')#主选择器
print(result)#[<title id="one">The Dormouse's story</title>, <p class="title"><b>The Dormouse's story</b></p>]

result=soup.select('a[id="link3"]')
print(result)#[<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

#取标签包裹的文本内容
result=soup.select('p')
print('*'*100)
for i in result:
    print(i)
result=soup.select('b')[0].get_text()

print(result,len(result))
print('*'*100)
result=soup.select('.title')[0].get_text()
print(result)
result=soup.select('.title')[0].string
print(result)


#标签的属性
result=soup.select('#link1')[0].get('href')
print(result)
for i in range(3):
    print(soup.select('a')[i].get_text(),soup.select('a')[i].get('href'))

###########
result=soup.select('a[id="link3"]')[0].get_text()
print(result)













